import { merge } from "lodash-es";
import { platform } from "../utils";
import { mapStore } from "../utils/store";
import { $http } from "../boot/http";
import { $config } from "../config";

export default merge(
  {
    namespaced: true,
    state: {
      versionShow: null,
      locale: null,
      locales: null
    },
    mutations: {
      setVersionShow(state, show) {
        state.versionShow = show;
      },
      setLocale(state, locale) {
        state.locale = locale;
      }
    },
    getters: {
      platform,
      version(_, { platform }) {
        return platform.version;
      },
      newVersion(_, { settings, version, platform }) {
        if (platform.app.app) {
          return (
            settings[`${platform.app.ios ? "ios" : "android"}_version`] ||
            version
          );
        }

        return version;
      },
      download(_, { platform, settings }) {
        if (platform.app.app) {
          return (
            settings[`${platform.app.ios ? "ios" : "android"}_download`] || ""
          );
        }

        return "";
      },
      i18n() {
        return true;
      },
      locale(state, getters) {
        return state.locale || getters[0] || "zh_CN";
      },
      locales(state) {
        return state.locales || $config.i18n.supportedLocales;
      }
    },
    actions: {
      async checkVersion({ dispatch, commit }, { force = false } = {}) {
        return dispatch(
          "toggleLoading",
          {
            key: "system.check.version",
            loading: async () => {
              await dispatch("loadSettings", { options: { force: true } });
              commit("setVersionShow", true);
            }
          },
          { root: true }
        );
      },
      async getLabel({ dispatch }, labelKey) {
        return dispatch(
          "toggleLoading",
          {
            key: "system.label",
            loading: async () => {
              const { data } = await $http.get("/api/v1/label/" + labelKey);
              return data;
            }
          },
          { root: true }
        );
      },
      async switchLocale({ commit }, { locale }) {
        commit("setLocale", locale);
      }
    }
  },
  mapStore("label", {
    url: "api/v1/label",
    options: {
      actionOptions: { commitType: "data", cacheState: true }
    }
  }),
  mapStore("settings", {
    url: "api/v1/settings",
    options: {
      actionOptions: { commitType: "data", cacheState: true }
    }
  })
);
